<template>
  <div class="merchant-container">
    <!-- 页面标题 -->
    <h2 class="page-title">我的民宿管理</h2>

    <!-- 搜索与筛选 -->
    <div class="search-container">
      <el-input v-model="searchQuery" placeholder="请输入民宿名称" @input="filterMinsu"></el-input>
      <el-select v-model="priceFilter" placeholder="选择价格区间" @change="filterMinsu">
        <el-option label="0-300" :value="[0, 300]"></el-option>
        <el-option label="300-600" :value="[300, 600]"></el-option>
        <el-option label="600以上" :value="[600, Infinity]"></el-option>
      </el-select>
    </div>

    <!-- 民宿列表 -->
    <div class="minsu-grid">
      <!-- 判断 paginatedMinsuList 是否为空 -->
      <template v-if="paginatedMinsuList.length > 0">
        <el-card v-for="(minsu, index) in paginatedMinsuList" :key="index" class="minsu-card">
          <div class="image-wrapper">
            <img :src="minsu.coverpicture || defaultImage" class="minsu-image" />
          </div>
          <div class="info">
            <h3 class="name">{{ minsu.hname }}</h3>
            <p class="address">地址: {{ minsu.address }}</p>
            <p class="price">价格: ￥{{ minsu.price }} / 晚</p>
            <p class="rating">评分: {{ minsu.grade }} ⭐</p>
            <p class="rating">评价: {{ minsu.gradeStatus }} </p>
            <p class="minsu-stock">库存：{{minsu.stock }} 间</p>
          </div>
          <div class="actions">
            <el-button type="primary" @click="editMinsu(minsu)">编辑</el-button>
            <el-button type="danger" @click="deleteMinsu(minsu.hid)">删除</el-button>
          </div>
        </el-card>
      </template>
      <!-- 如果 paginatedMinsuList 为空，显示提示信息 -->
      <template v-else>
        <div class="empty-message">
          <p>暂无民宿数据，请添加或调整筛选条件。</p>
        </div>
      </template>



       <!-- 删除确认弹窗 -->
  <el-dialog
      title="确认删除"
      :visible.sync="deledialogVisible"
    >
      <p style="font-size: 26px;">确定要删除该民宿吗？删除后不可恢复！</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deledialogVisible = false">取消</el-button>
        <el-button type="danger" @click="deleteHotel">确认删除</el-button>
      </span>
    </el-dialog>


    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="filteredMinsuList.length"
        @current-change="handlePageChange"
        layout="prev, pager, next">
      </el-pagination>
    </div>

    <!-- 添加民宿按钮 -->
    <div class="add-button">
      <el-button type="success" @click="openAddDialog">添加新民宿</el-button>
    </div>

    <!-- 编辑/添加民宿弹窗 -->
    <el-dialog :title="editMode ? '编辑民宿信息' : '添加新民宿'" :visible.sync="showMinsuDialog" width="50%">
      <el-form :model="currentMinsu" label-width="100px">
        <el-form-item label="名称">
          <el-input v-model="currentMinsu.hname" placeholder="请输入民宿名称" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="currentMinsu.address" placeholder="请输入民宿地址" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="currentMinsu.phonenumber" placeholder="请输入民宿联系电话" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number v-model="currentMinsu.price" :min="0" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="评分">
          <el-input-number v-model="currentMinsu.grade" :min="0" :max="5" :step="0.1" placeholder="请输入评分" />
        </el-form-item>
        <el-form-item label="房间库存">
          <el-input-number v-model="currentMinsu.stock" :min="0"  :step="1" placeholder="请输入剩余房间" />
        </el-form-item>

        <!-- 图片上传部分 -->
        <el-form-item label="图片" v-if="insert">
          <el-upload class="upload-demo"
           action="" 
           list-type="picture-card" 
           :file-list="currentMinsu.imageList"
           :auto-upload="false"
           :on-change="handleImageChange" 
           :on-remove="handleImageRemove">

            <i slot="default" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeMinsuDialog">取消</el-button>
        <el-button type="primary" @click="saveMinsu">保存</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import { uploadHomeStay,selectAllHomeStaybyID, editHomeStay,deleteHomeStay } from "@/api/homestay.ts";

export default {
  data() {
    return {
      minsuList: [],
      defaultImage: "https://via.placeholder.com/300x200?text=默认图片",
      showMinsuDialog: false, 
      currentMinsu: {
        hid:'',
        hname: '',
        address: '',
        price: null,
        grade: null,
        phonenumber: '',
        imageList: [],
        stock:''
      },
      editMode: false, 
      searchQuery: '',
      priceFilter: null,
      currentPage: 1,
      pageSize: 5,
      insert:true,
      deledialogVisible:false,
      deleteid:''
    };
  },
  computed: {
  filteredMinsuList() {
    let filteredList = this.minsuList || []; // 确保 filteredList 是一个数组
    
    // 根据搜索条件筛选
    if (this.searchQuery) {
      filteredList = filteredList.filter(minsu => 
        minsu.hname && minsu.hname.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    }
    
    // 根据价格筛选
    if (this.priceFilter) {
      const [minPrice, maxPrice] = this.priceFilter;
      filteredList = filteredList.filter(minsu => 
        minsu.price >= minPrice && minsu.price <= maxPrice
      );
    }

    return filteredList;
  },
  paginatedMinsuList() {
    const startIndex = (this.currentPage - 1) * this.pageSize;
    const list = this.filteredMinsuList || []; // 确保 list 是一个数组
    return list.slice(startIndex, startIndex + this.pageSize);
  }
},
mounted() {
  selectAllHomeStaybyID(JSON.parse(localStorage.getItem('currentUser')).uid)
    .then(res => {
      this.minsuList = res.data.data || []; // 确保 minsuList 是一个数组
    })
    .catch(error => {
      console.error("加载民宿数据失败", error);
      this.minsuList = []; // 如果请求失败，设置为空数组
    });
},
  methods: {
    // 处理搜索与筛选
    filterMinsu() {
      this.currentPage = 1; // 重置分页
    },

    // 分页切换
    handlePageChange(page) {
      this.currentPage = page;
    },

    // 编辑民宿
    editMinsu(minsu) {
      this.currentMinsu =  minsu;
      this.editMode = true;
      this.insert=false;
      this.showMinsuDialog = true;
    },

    // 删除民宿
    deleteMinsu(id) {
      this.deleteid=id,
      this.deledialogVisible=true
    },
    deleteHotel(){
      deleteHomeStay(this.deleteid)
      .then(res => {
          if (res.data.code === 1) {
            this.deledialogVisible = false; 
            this.deleteid="",
            this.$message.success("删除成功！");
            selectAllHomeStaybyID(JSON.parse(localStorage.getItem('currentUser')).uid).then(res => {
              this.minsuList = res.data.data;
            });
          } else {
            this.$message.error(res.data.message || "删除失败！");
          }
        })
        .catch(error => {
          console.error("删除失败", error);
          this.$message.error("删除失败，请重试！");
        });
    },

    // 打开添加民宿弹窗
    openAddDialog() {
      this.currentMinsu = {
        name: "",
        address: "",
        price: null,
        rating: null,
        imageList: [],
        phonenumber: "",
        stock:''
      };
      this.editMode = false;
      this.insert=true,
      this.showMinsuDialog = true;
    },

    // 保存民宿信息
    saveMinsu() {
      const formData = new FormData();

      if(this.insert){
        if (this.currentMinsu.imageList && this.currentMinsu.imageList.length > 0) {
        formData.append("pic", this.currentMinsu.imageList[0].raw); 
      }

      formData.append("hotel", JSON.stringify({
        fid: JSON.parse(localStorage.getItem("currentUser")).uid,
        hname: this.currentMinsu.hname,
        grade: this.currentMinsu.grade,
        price: this.currentMinsu.price,
        address: this.currentMinsu.address,
        stock:this.currentMinsu.stock,
        phonenumber: this.currentMinsu.phonenumber,
      }));

      uploadHomeStay(formData)
        .then(res => {
          if (res.data.code === 1) {
            this.showMinsuDialog = false; 
            this.currentMinsu = {
              hname: "",
              address: "",
              price: null,
              grade: null,
              imageList: [],
              phonenumber: "",
              stock:''
            };
            this.$message.success("发布成功！");
            selectAllHomeStaybyID(JSON.parse(localStorage.getItem('currentUser')).uid).then(res => {
              this.minsuList = res.data.data;
            });
          } else {
            this.$message.error(res.data.message || "发布失败！");
          }
        })
        .catch(error => {
          console.error("上传失败", error);
          this.$message.error("上传失败，请重试！");
        });
      }else{
        formData.append("newhotel",JSON.stringify({
          hid:this.currentMinsu.hid,
          hname: this.currentMinsu.hname,
          grade: this.currentMinsu.grade,
          price: this.currentMinsu.price,
          address: this.currentMinsu.address,
          stock:this.currentMinsu.stock,
          phonenumber: this.currentMinsu.phonenumber,
        }))
        editHomeStay(formData)
          .then(res=>{
            if (res.data.code === 1) {
            this.showMinsuDialog = false; 
            this.currentMinsu = {
              hid:"",
              hname: "",
              address: "",
              price: null,
              grade: null,
              imageList: [],
              phonenumber: "",
              stock:''
            };
            this.$message.success("发布成功！");
            selectAllHomeStaybyID(JSON.parse(localStorage.getItem('currentUser')).uid).then(res => {
              this.minsuList = res.data.data;
            });
          } else {
            this.$message.error(res.data.message || "发布失败！");
          }
          })
      }
     
    },

    // 切换民宿的上下架状态
    toggleStatus(minsu) {
      minsu.status = minsu.status === "active" ? "archived" : "active";
    },

    // 上传图片的变化事件
    handleImageChange(file, fileList) {
      console.log("图片加1")
      this.currentMinsu.imageList = fileList; 
    },

    // 移除图片的回调
    handleImageRemove(file, fileList) {
      this.currentMinsu.imageList = fileList; 
    },

    // 关闭弹窗
    closeMinsuDialog() {
      this.showMinsuDialog = false;
    },
  },
};
</script>

<style>
.merchant-container {
  padding: 20px;
}

.page-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.search-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.minsu-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.minsu-card {
  border-radius: 10px;
  overflow: hidden;
  transition: transform 0.2s;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.minsu-card:hover {
  transform: translateY(-5px);
}

.image-wrapper {
  width: 100%;
  height: 150px;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.minsu-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

.info {
  padding: 10px;
}

.name {
  font-size: 18px;
  font-weight: bold;
  margin: 5px 0;
}

.address {
  font-size: 14px;
  color: #666;
}

.price {
  font-size: 16px;
  color: #f56c6c;
}

.rating {
  font-size: 14px;
  color: #f5a623;
}
.minsu-stock {
  font-size: 12px;
  color: #388e3c;
}

.actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.add-button {
  text-align: center;
  margin-top: 20px;
}

.pagination-container {
  text-align: center;
  margin-top: 20px;
}
</style>